import { Component } from '@angular/core';
import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';
import { Http, Headers } from '@angular/http'

@Component({
    selector: 'test-from',
    templateUrl: 'app/components/form/form.component.html'
})
export class FormComponent {
    loginForm: FormGroup;
    authenticated: boolean
    profile: Object;

    constructor(fb: FormBuilder, private http: Http) {
        if (localStorage.getItem('jwt')) {
            this.authenticated = true;
            this.profile = JSON.parse(localStorage.getItem('profile'));
        }
        this.loginForm = fb.group({
            'email': [null, this.containsMagicWord],
            'password': [null, Validators.compose([Validators.required, Validators.maxLength(6)])],
        })
    }
    private containsMagicWord(c: FormControl) {
        let content: string;
        content = c.value;
        if (content != null && content.indexOf('magic') >= 0) {
            console.log('not valid')
            return {
                noMagic: true
            }
        }

        // Null means valid, believe it or not
        console.log('valid')
        return null
    }
    submitForm(value: any) {
        let form = {
            'client_id': 'YOUR-AUTH0-CLIENT-ID',
            'username': value.email,
            'password': value.password,
            'connection': 'YOUR-DATABASE-CONNECTION-NAME',
            'grant_type': 'password',
            'scope': 'openid name email'
        }
        let userInfo = {
            'username': value.email,
            'password': value.password
        };
        let header = new Headers();
        header.append('Content-Type', 'application/json; charset=utf-8')
        this.http.post('/api/Account/authenticate', userInfo, { headers: header }).subscribe(
            (res: any) => {
                let data = res.json();
                console.log(data);
            },
            (error: any) => {
                console.log(error);
            }
        );
        // this.http.post('https://YOUR-AUTH0-DOMAIN.auth0.com/oauth/ro', form).subscribe(
        //   (res:any)=>{
        //     let data = res.json();
        //     if(data.id_token){
        //       localStorage.setItem('jwt', data.id_token);
        //       this.getUserInfo(data);
        //     }
        //   }
        // )
    }

    getUserInfo(data: any) {
        let form = {
            'id_token': data.id_token
        }
        // this.http.post('https://YOUR-AUTH0-DOMAIN.auth0.com/tokeninfo', form).subscribe(
        //   (res:any)=>{
        //     let data = res.json();
        //     this.profile = data;
        //     localStorage.setItem('profile', JSON.stringify(data));
        //     this.authenticated = true;
        //     this.loginForm.reset();
        //   }
        // )
    }

    logout() {
        localStorage.removeItem('jwt');
        localStorage.removeItem('profile');
        this.authenticated = false;
    }
}
